package com.kevin.demo.generate.base;

import com.google.common.collect.Maps;
import com.kevin.demo.utils.CodeGeneratorUtil;
import com.kevin.demo.utils.ContextUtil;
import org.apache.commons.configuration.Configuration;

import java.sql.*;
import java.util.*;

/**
 * @author: e20160504
 * @date: 2018/7/24
 * @desc
 */
public class GenerateService {

    public static Configuration config = ContextUtil.getConfig("generator.properties");

    public static void main(String[] args) throws Exception {
        String tableName = config.getString("table_name");

        //查询表信息
        Map<String, String> table = getTableInfo(tableName).get(0);
        //查询列信息
        List<Map<String, String>> columns = listColumns(tableName);
        //生成代码
        CodeGeneratorUtil.generatorCode(table, columns);

    }


    //public static void main(String[] args) throws Exception {
    //    List<Map<String, String>> result = listColumns("sys_user_test");
    //    for (Map<String, String> colums : result) {
    //        Iterator<Map.Entry<String, String>> it = colums.entrySet().iterator();
    //        while (it.hasNext()) {
    //            Map.Entry<String, String> entry = it.next();
    //            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
    //        }
    //    }
    //
    //}

    /**
    *@params: 表名
    *@return: 表信息
    *@desc:   获取表的元数据
    */
    private static List<Map<String, String>> getTableInfo(String tableName) throws Exception {
        Connection conn = getConn();
        String sql = "select table_name tableName, table_comment tableComment from information_schema.tables where table_schema = (select database()) and table_name = '" + tableName + "'";
        List<Map<String, String>> result = getResult(conn, sql);
        conn.close();
        return result;
    }

    /**
    *@params: 表名
    *@return: 表列信息
    *@desc:   获取表的列信息
    */
    private static List<Map<String, String>> listColumns(String tableName) throws Exception {
        Connection conn = getConn();
        String sql = "select column_name columnName, data_type dataType, column_comment columnComment, column_key columnKey, extra from information_schema.columns where table_name = '" + tableName + "' and table_schema = (select database()) order by ordinal_position";
        List<Map<String, String>> result = getResult(conn, sql);
        conn.close();
        return result;
    }


    /**
    *@params:
    *@return:
    *@desc: 数据库交互
    */
    private static List<Map<String, String>> getResult(Connection conn, String sql) throws Exception {
        System.out.println(sql);
        PreparedStatement pstmt;
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        int count = metaData.getColumnCount();

        List<Map<String, String>> resultList = new ArrayList<>();
        while (rs.next()) {
            Map<String, String> resultMap = Maps.newHashMap();
            //使用随机数使key不重复
            double plus = Math.random();
            int colLen = metaData.getColumnCount();
            for (int i = 1; i <= colLen; i++) {
                String columnLable = metaData
                        .getColumnLabel(i);
                String columnValue = rs.getString(i);
                resultMap.put(columnLable, columnValue);
            }
            resultList.add(resultMap);
        }
        return resultList;
    }


    /**
    *@params:
    *@return:
    *@desc: 得到一个连接
    */
    private static Connection getConn() {

        String driver = config.getString("driver");
        String url = config.getString("url");
        String username = config.getString("username");
        String password = config.getString("password");
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
